package com.xpgk.common.kit;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Properties;

import com.jfinal.core.Const;
import com.jfinal.kit.LogKit;

public class PasswordKit {
	static private PasswordKit m_PasswordKit = new PasswordKit();
	private Properties m_properties = null;
	private String m_fileName = null;

	static public PasswordKit use(String fileName) {
		m_PasswordKit.m_fileName = fileName;
		InputStream inputStream = null;
		try {
			inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(fileName); // properties.load(Prop.class.getResourceAsStream(fileName));
			if (inputStream == null)
				throw new IllegalArgumentException("Properties file not found in classpath: " + fileName);
			m_PasswordKit.m_properties = new Properties();
			m_PasswordKit.m_properties.load(new InputStreamReader(inputStream, Const.DEFAULT_ENCODING));
		} catch (IOException e) {
			throw new RuntimeException("Error loading properties file.", e);
		} finally {
			if (inputStream != null)
				try {
					inputStream.close();
				} catch (IOException e) {
					LogKit.error(e.getMessage(), e);
				}
		}
		return m_PasswordKit;
	}

	// 得到密码，如果密码为明码，则自动加密保存
	// PasswordKit.use(file).getPassword(key);
	static public String getPassword(String key) {
		if (m_PasswordKit.m_properties == null)
			return null;
		// throw new Exception("请先调用use");
		String pwd = m_PasswordKit.m_properties.getProperty(key);
		if (pwd != null) {
			if (m_PasswordKit.IsPasswordEncrypt(pwd)) {
				pwd = m_PasswordKit.Decrypt(pwd);
			} else {
				try {
					SavePassword(key, m_PasswordKit.Encrypt(pwd));
				} catch (Exception e) {

				}
			}
		}
		return pwd;
	}

	static public boolean SavePassword(String key, String password) {
		return setProp(key, m_PasswordKit.Encrypt(password));
	}

	static public boolean setProp(String key, String value) {
		if (m_PasswordKit.m_properties == null)
			return false;
		boolean bRet = false;
		try {
			String path = Thread.currentThread().getContextClassLoader().getResource(m_PasswordKit.m_fileName)
					.getPath();
			File file = new File(path);
			// read file content from file
			StringBuffer sb = new StringBuffer("");
			FileReader reader = new FileReader(file);
			BufferedReader br = new BufferedReader(reader);

			String str = null;
			while ((str = br.readLine()) != null) {
				if (str.startsWith(key)) {
					bRet = true;
					str = str.substring(0, str.indexOf("="));
					if (str != null && str.trim().equals(key))
						str += " = " + value;
				}
				sb.append(str + "\n");
			}
			br.close();
			reader.close();

			if (!bRet)
				sb.append(key + " = " + value + "\n");

			// write string to file
			FileWriter writer = new FileWriter(file);
			BufferedWriter bw = new BufferedWriter(writer);
			bw.write(sb.toString());

			bw.close();
			writer.close();
			return true;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

	private boolean IsPasswordEncrypt(String pwd) {
		if (pwd != null && pwd.startsWith("@#$"))
			return true;
		return false;
	}

	private String Encrypt(String pwd) {
		if (pwd == null)
			return null;
		if (pwd.startsWith("@#$"))
			return pwd;
		pwd = "@#$" + EncryptKit.encrypt(pwd);
		return pwd;
	}

	private String Decrypt(String pwd) {
		if (pwd == null || !pwd.startsWith("@#$"))
			return null;
		pwd = EncryptKit.decrypt(pwd.substring(3));
		return pwd;
	}

}
